
const TOKEN_HEADNAME = "Authorization";
const URL = location.href.indexOf('localhost') ? ' http://localhost:61337' : 'http://api.juzhen.net';


/**
 * 处理json数据为...
 */

var escape = encodeURIComponent;

const isArry = function (value) {
    return value instanceof Array
}

const isObject = function (value) {
    return value instanceof Object
}

const serialize = function (params, obj, traditional, scope) {
    var array = isArry(obj);

    for (let key in obj) {
        let value = obj[key];
        if (scope) {
            key = traditional ? scope : scope + '[' + (array ? '' : key) + ']'
        }

        if (!scope && array) {
            params.add(value.name, value.value)
        } else if (traditional ? isArry(value) : isObject(value)) {
            serialize(params, value, traditional, key)
        } else {
            params.add(key, value)
        }
    }

}


const serializeData = function (obj, traditional) {
    var params = []
    params.add = function (k, v) { this.push(escape(k) + '=' + escape(v)) }
    serialize(params, obj, traditional)
    return params.join('&').replace('%20', '+')
}


/**
 * ajax请求封装
 * token与userinfo逻辑的封装
 * 
 * @param {*} params // {method,url,jsonData}
 * @param {*} cb 
 */
const weAjax = (params, cb) => {

    var xmlhttp = new XMLHttpRequest();

    // 监听数据请求
    xmlhttp.onload = function (event) {

        if (event.target.getResponseHeader("Content-Type") === "application/json") {
            var jsonData = JSON.parse(event.target.responseText);
            if (jsonData.token) {
                // 每次请求都要更新token
                localStorage.setItem(TOKEN_HEADNAME, jsonData.token);
            }
            cb(jsonData);
        } else {
            cb(event.target.responseText);
        }

    }

    // 监听数据错误
    xmlhttp.onerror = xmlhttp.onabort = function (event) {
        alert('Something is wrong')
    }

    // 默认为post方法
    params.method = params.method || 'post';
    params.method = params.method.toLowerCase();
    params.async = params.async || true;

    // 处理请求地址
    let requestUrl = params.url;
    if (requestUrl) {
        if (params.query) {  // 查询字符串格式化

            var queryList = [];
            for (let i in params.query) {
                queryList.push(i + '=' + encodeURI(params.query[i]))
            }
            requestUrl = requestUrl + '?' + queryList.join('&');
        }

        xmlhttp.open(params.method, URL + requestUrl, params.async);

        if (params.method === "post") { // 会出现跨域prefilte
            xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
            // xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'OPTIONS,GET,POST');
            // xmlhttp.setRequestHeader('Allow', 'OPTIONS,GET,POST');
        }
    } else {
        return console.error('Url Error !')
    }

    // 处理请求数据
    if (params.data) {
        params.data.token = localStorage.getItem(TOKEN_HEADNAME);
        xmlhttp.send(serializeData(params.data));
    } else {
        xmlhttp.send();
    }

    return xmlhttp;
}


export default weAjax;

